package com.doyoulike.config.mybatis;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * MyBatis 数据源配置类
 *
 * @Configuration 表示是一个配置类
 * @Primary 表示是主数据源
 * @Bean("businessSqlSessionTemplate") 表示 将这个对象放入 Spring 容器
 * @Qualifier 表示查找 Spring 容器中名字为 businessDateSource 的对象
 */
@Configuration
@MapperScan(basePackages ="com.doyoulike.dao.business", sqlSessionTemplateRef  = "businessSqlSessionTemplate")
public class MyBatisBusinessConfig {

    @Bean("businessDateSource")
    @ConfigurationProperties(prefix = "spring.datasource.business")
    public DataSource getPrimaryDateSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "businessSqlSessionFactory")
    public SqlSessionFactory businessSqlSessionFactory(@Qualifier("businessDateSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/business/*.xml"));
        return bean.getObject();
    }

    @Bean("businessSqlSessionTemplate")
    public SqlSessionTemplate businesssqlsessiontemplate(@Qualifier("businessSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }

}
